package com.minio.it.config;

import com.minio.it.model.FileVO;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
public class MinioSysFileUploadUtils {
 
    // 注入minio配置文件
    @Autowired
    private MinioConfig minioConfig;
 
    // 注入minio client
    @Autowired
    private MinioClient client;

    public FileVO upload(MultipartFile file, String folder) {
        FileVO fileVO = new FileVO();
        try {
            // 获取文件真实名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件的扩展名 例如.jpg .doc
            String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extname;
            // 如果需要的话，可以在这里对folder变量进行处理，比如去除前后空格或者斜杠等
            if (!folder.endsWith("/")) {
                folder += "/";
            }
            // 构建文件上传相关信息
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(folder + fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            // 将文件上传到minio服务器
            client.putObject(args);
            // 组装文件信息，返回前端 或者存入数据路
            String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + folder + fileName;
            fileVO.setUrl(url);
            fileVO.setSize(file.getSize());
            fileVO.setFileName(fileName);
            fileVO.setExtname(extname);
        } catch (Exception e) {
            throw new RuntimeException("文件上传异常" + e.getCause().toString());
        }
        return fileVO;
    }
}